import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

// 设置默认请求ip地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(config => {
  // 有token就设置token
  if (store.state.user.token) {
    config.headers.Authorization = 'Bearer ' + store.state.user.token
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(res => {
  // 请求回来的结果进行判定
  if (res.data.success) {
    return res.data.data
  } else {
    Message.error(res.data.message)
    return Promise.reject(new Error(res.data.message))
  }
}, err => {
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/removeUserList')
    router.push('/login')
  }
  Message.error(err.message)
  return Promise.reject(new Error(err.message))
})

export default service
